package com.ruicar.afs.cloud.manage.finance.corporate.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.basic.api.corporate.fegin.CorporateTransferFeign;
import com.ruicar.afs.cloud.common.config.ContractFeginConfig;
import com.ruicar.afs.cloud.common.core.exception.AfsBaseException;
import com.ruicar.afs.cloud.common.core.uid.AfsSequenceGenerator;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.common.modules.contract.enums.*;
import com.ruicar.afs.cloud.common.util.EmptyUtils;
import com.ruicar.afs.cloud.manage.common.entity.ManageApplyRecord;
import com.ruicar.afs.cloud.manage.common.entity.ManageApprovalRecord;
import com.ruicar.afs.cloud.manage.common.service.ManageApplyRecordService;
import com.ruicar.afs.cloud.manage.common.service.ManageApprovalRecordService;
import com.ruicar.afs.cloud.manage.finance.corporate.entity.ManageCorporateTransfer;
import com.ruicar.afs.cloud.manage.finance.corporate.service.ManageCorporateTransferService;
import com.ruicar.afs.cloud.manage.outer.api.corporate.dto.CorporateTransferOperateDto;
import com.ruicar.afs.cloud.manage.outer.api.corporate.dto.ManageCorporateTransferClone;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;

/**
 * <p>Description: </p>
 *
 * @author ZC.GUO
 * @version 1.0
 * @date create on 2020-07-21 20:04
 */
@Slf4j
@RestController
@Api("对公结算管理")
@RequestMapping("/corporateTrans")
@AllArgsConstructor
public class CorporateTransForApplyController {

    private final ManageCorporateTransferService manageCorporateTransferService;
    private final CorporateTransferFeign corporateTransferFeign;
    private final ContractFeginConfig contractFeginConfig;
    private final AfsSequenceGenerator afsSequenceGenerator;
    private final ManageApprovalRecordService manageApprovalRecordService;
    private final ManageApplyRecordService manageApplyRecordService;

    /**
     * 多条件分页获取对公勾稽案件信息
     * @author ZC.GUO
     * @param
     * @return
     */
    @PostMapping(value = "/queryCorporateList")
    @ApiOperation(value = "多条件分页获取对公勾稽案件信息")
    public IResponse<IPage<ManageCorporateTransfer>> queryCorporateList(@RequestBody CorporateTransferOperateDto corporateTransferOperateDto) {
        if (EmptyUtils.isNotEmpty(corporateTransferOperateDto.getStartTimeS())){
            corporateTransferOperateDto.setStartTimeS(DateUtil.beginOfDay(corporateTransferOperateDto.getStartTimeS()));
        }
        if (EmptyUtils.isNotEmpty(corporateTransferOperateDto.getStartTimeE())){
            corporateTransferOperateDto.setStartTimeE(DateUtil.endOfDay(corporateTransferOperateDto.getStartTimeE()));
        }

        LambdaQueryWrapper<ManageCorporateTransfer> queryWrapper = Wrappers.<ManageCorporateTransfer>query().lambda()
                .like(EmptyUtils.isNotEmpty(corporateTransferOperateDto.getCaseNo()),ManageCorporateTransfer::getCaseNo,corporateTransferOperateDto.getCaseNo())
                .like(EmptyUtils.isNotEmpty(corporateTransferOperateDto.getCustName()),ManageCorporateTransfer::getCustName,corporateTransferOperateDto.getCustName())
                .eq(EmptyUtils.isNotEmpty(corporateTransferOperateDto.getReceivingBank()),ManageCorporateTransfer::getReceivingBank,corporateTransferOperateDto.getReceivingBank())
                .ge(EmptyUtils.isNotEmpty(corporateTransferOperateDto.getStartTimeS()),ManageCorporateTransfer::getStartTime,corporateTransferOperateDto.getStartTimeS())
                .le(EmptyUtils.isNotEmpty(corporateTransferOperateDto.getStartTimeE()),ManageCorporateTransfer::getStartTime,corporateTransferOperateDto.getStartTimeE())
                .eq(ManageCorporateTransfer::getCreateBy, corporateTransferOperateDto.getCurrentUserName())
                .eq(ManageCorporateTransfer::getCaseSource, CaseSourceEnum.CHANNAL)
                .eq(EmptyUtils.isNotEmpty(corporateTransferOperateDto.getCaseStatus()),ManageCorporateTransfer::getCaseStatus,corporateTransferOperateDto.getCaseStatus());
        if (!corporateTransferOperateDto.getAllCase()&&EmptyUtils.isEmpty(corporateTransferOperateDto.getCaseStatus())){
            /**  非全部案件并且无指定状态时只查询审批拒绝的案件 by ZC.GUO  **/
            queryWrapper.eq(ManageCorporateTransfer::getCaseStatus, CaseStatusEnum.REFUSE);
        }
        queryWrapper.orderByAsc(ManageCorporateTransfer::getStartTime);

        Page page = new Page(corporateTransferOperateDto.getPageNumber(), corporateTransferOperateDto.getPageSize());
        IPage<ManageCorporateTransfer> manageCorporateTransferIPage = manageCorporateTransferService.page(page, queryWrapper);
        return IResponse.success(manageCorporateTransferIPage);
    }
    /**
     * 删除对公案件
     * @author ZC.GUO
     * @param
     * @return
     */
    @PostMapping(value = "/deleteCorporateTransfer")
    @ApiOperation(value = "删除对公案件")
    public IResponse deleteCorporateTransfer(@RequestParam("id") Long id) {

        ManageCorporateTransfer manageCorporateTransfer = manageCorporateTransferService.getById(id);
        if (manageCorporateTransfer != null && CaseStatusEnum.NOT_SUBMIT.equals(manageCorporateTransfer.getCaseStatus())){
            manageCorporateTransferService.removeById(manageCorporateTransfer.getId());
            return IResponse.success("删除成功");
        }else{
            return IResponse.fail("删除失败");
        }
    }



    /**
     * 对公勾稽案件信息保存
     * @author ZC.GUO
     * @param
     * @return
     */
    @PostMapping(value = "/saveCorporate")
    @ApiOperation(value = "对公勾稽案件信息保存")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<ManageCorporateTransfer> saveCorporate(@RequestBody ManageCorporateTransferClone manageCorporateTransferClone) {
        ManageCorporateTransfer corporateTransfer = new ManageCorporateTransfer();
        BeanUtils.copyProperties(manageCorporateTransferClone,corporateTransfer);
        corporateTransfer.setCreateBy(manageCorporateTransferClone.getUsername());
        /**  生成案件编号 by ZC.GUO  **/
        if (EmptyUtils.isEmpty(corporateTransfer.getCaseNo())){
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            Long seqNo = afsSequenceGenerator.genNext("DGJS",dateFormat.format(Calendar.getInstance().getTime()));
            String seqStr = StringUtils.leftPad(seqNo.toString(),4,"0");
            String caseNo = "DGJS" + dateFormat.format(Calendar.getInstance().getTime()) + seqStr;
            corporateTransfer.setCaseNo(caseNo);

        }
        /**  案件状态 by ZC.GUO  **/
        corporateTransfer.setCaseStatus(CaseStatusEnum.NOT_SUBMIT);
        corporateTransfer.setIsOperating(YesOrNoEnum.no);

        manageCorporateTransferService.saveOrUpdate(corporateTransfer);


        /**  保存变更操作记录数据 by ZC.GUO  **/
        ManageApplyRecord applyRecord = manageApplyRecordService.getOne(Wrappers.<ManageApplyRecord>lambdaQuery()
                .eq(ManageApplyRecord::getCaseNo, corporateTransfer.getCaseNo()));
        if (EmptyUtils.isNotEmpty(applyRecord)){
            applyRecord.setCaseStatus(CaseStatusEnum.NOT_SUBMIT);
            manageApplyRecordService.updateById(applyRecord);
        }else{
            ManageApplyRecord record = new ManageApplyRecord();
            record.setContractNo(corporateTransfer.getContractNo());
            record.setCaseNo(corporateTransfer.getCaseNo());
            record.setContractBusiness(CaseTypeEnum.BEFORE_CHARGE.equals(corporateTransfer.getCaseType())?ContractBusinessEnum.corporateSettlementPrepayment:ContractBusinessEnum.corporateSettlementRent);
            record.setCaseStatus(CaseStatusEnum.NOT_SUBMIT);
            record.setDataSource(corporateTransfer.getDataSource());
            record.setBusinessSource(corporateTransfer.getCaseSource());
            record.setApplyTime(DateUtil.date());
            record.setEndDate(Calendar.getInstance().getTime());
            manageApplyRecordService.save(record);
        }

        if (EmptyUtils.isEmpty(corporateTransfer)){
            corporateTransfer = new ManageCorporateTransfer();
        }
        return IResponse.success(corporateTransfer);
    }
    /**
     * 对公勾稽案件信息提交
     * @author ZC.GUO
     * @param
     * @return
     */
    @PostMapping(value = "/submitCorporate")
    @ApiOperation(value = "对公勾稽案件信息提交")
    @Transactional(rollbackFor = Exception.class)
    public IResponse<String> submitCorporate(@RequestBody ManageCorporateTransferClone manageCorporateTransferClone) {
        /**  合同关闭（审核中、审批通过） by ZC.GUO  **/
        List<ManageApplyRecord> list = manageApplyRecordService.list(Wrappers.<ManageApplyRecord>lambdaQuery()
                .eq(ManageApplyRecord::getContractNo, manageCorporateTransferClone.getContractNo())
                .eq(ManageApplyRecord::getContractBusiness, ContractBusinessEnum.closeContract)
                .in(ManageApplyRecord::getCaseStatus, CaseStatusEnum.UNDER_REVIEW, CaseStatusEnum.APPROVED));
        if (list.size() > 0) {
            throw new AfsBaseException("合同关闭业务审核中，无法审批！");
        }

        ManageCorporateTransfer corporateTransfer = new ManageCorporateTransfer();
        BeanUtils.copyProperties(manageCorporateTransferClone,corporateTransfer);
        corporateTransfer.setCreateBy(manageCorporateTransferClone.getUsername());
        /**  生成案件编号 by ZC.GUO  **/
        if (EmptyUtils.isEmpty(corporateTransfer.getCaseNo())){
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
            Long seqNo = afsSequenceGenerator.genNext("DGJS",dateFormat.format(Calendar.getInstance().getTime()));
            String seqStr = StringUtils.leftPad(seqNo.toString(),4,"0");
            String caseNo = "DGJS" + dateFormat.format(Calendar.getInstance().getTime()) + seqStr;
            corporateTransfer.setCaseNo(caseNo);
        }
        /**  案件状态 by ZC.GUO  **/
        corporateTransfer.setCaseStatus(CaseStatusEnum.UNDER_REVIEW);
        /**  开始时间 by ZC.GUO  **/
        corporateTransfer.setStartTime(Calendar.getInstance().getTime());
        corporateTransfer.setIsOperating(YesOrNoEnum.no);

        manageCorporateTransferService.saveOrUpdate(corporateTransfer);

        /**  保存变更操作记录数据 by ZC.GUO  **/
        ManageApplyRecord applyRecord = manageApplyRecordService.getOne(Wrappers.<ManageApplyRecord>lambdaQuery()
                .eq(ManageApplyRecord::getCaseNo, corporateTransfer.getCaseNo()));
        if (EmptyUtils.isNotEmpty(applyRecord)){
            applyRecord.setCaseStatus(CaseStatusEnum.UNDER_REVIEW);
            manageApplyRecordService.updateById(applyRecord);
        }else{
            ManageApplyRecord record = new ManageApplyRecord();
            record.setContractNo(corporateTransfer.getContractNo());
            record.setCaseNo(corporateTransfer.getCaseNo());
            record.setContractBusiness(CaseTypeEnum.BEFORE_CHARGE.equals(corporateTransfer.getCaseType())?ContractBusinessEnum.corporateSettlementPrepayment:ContractBusinessEnum.corporateSettlementRent);
            record.setCaseStatus(CaseStatusEnum.UNDER_REVIEW);
            record.setDataSource(corporateTransfer.getDataSource());
            record.setBusinessSource(corporateTransfer.getCaseSource());
            record.setApplyTime(DateUtil.date());
            record.setEndDate(Calendar.getInstance().getTime());
            manageApplyRecordService.save(record);
        }

        /**  保存操作流水 by ZC.GUO  **/
        ManageApprovalRecord approvalRecord = new ManageApprovalRecord();
        approvalRecord.setContractNo(corporateTransfer.getContractNo());
        approvalRecord.setCaseNo(corporateTransfer.getCaseNo());
        approvalRecord.setContractBusiness(CaseTypeEnum.BEFORE_CHARGE.equals(corporateTransfer.getCaseType())?ContractBusinessEnum.corporateSettlementPrepayment:ContractBusinessEnum.corporateSettlementRent);
        approvalRecord.setProcessPerson(manageCorporateTransferClone.getUserRealName());
        approvalRecord.setDepartment(manageCorporateTransferClone.getDeptId());

        approvalRecord.setProcessNode(null);
        approvalRecord.setNodeName("发起对公结算");
        approvalRecord.setApprovalOpinion("发起对公结算");
        manageApprovalRecordService.save(approvalRecord);

        return IResponse.success("提交成功");
    }

    /**
     * 根据案件编号查询对公结算案件详情
     * @author ZC.GUO
     * @param
     * @return
     */
    @PostMapping(value = "/queryCorporateByCaseNo")
    @ApiOperation(value = "根据案件编号查询对公结算案件详情")
    public IResponse queryCorporateByCaseNo(@RequestParam("caseNo") String caseNo) {
        ManageCorporateTransfer manageCorporateTransfer = manageCorporateTransferService.getOne(Wrappers.<ManageCorporateTransfer>query().lambda()
                .eq(ManageCorporateTransfer::getCaseNo,caseNo)
        );
        if (EmptyUtils.isEmpty(manageCorporateTransfer)){
            manageCorporateTransfer = new ManageCorporateTransfer();
        }
        return IResponse.success(manageCorporateTransfer);
    }
}
